package cc.eddic.practice.concurrency.impl;

import cc.eddic.practice.concurrency.CdnLogItem;
import cc.eddic.practice.concurrency.CdnLogParser;
import cc.eddic.practice.concurrency.LogItem;
import cc.eddic.practice.concurrency.LogParser;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.nio.file.Files;
import java.util.*;
import java.util.zip.GZIPInputStream;

@Slf4j
public class CdnLogParserWithLoopImpl implements CdnLogParser {
    @Override
    public Map<String, List<CdnLogItem>> parse(String folderName) {
        Map<String, List<CdnLogItem>> resultMap = new HashMap<>();
        processFolder(new File(folderName), resultMap);
        return resultMap;
    }

    private void processFolder(File folder, Map<String, List<CdnLogItem>> resultMap) {
        if (folder.isDirectory()) {
            File[] files = folder.listFiles((dir, name) -> name.endsWith(".gz"));

            if (files != null) {
                CdnLogItemParserImpl cdnLogItemParser = new CdnLogItemParserImpl();

                for (File file : files) {
                    String filePath = file.getAbsolutePath();
                    List<CdnLogItem> cdnLogItems = new ArrayList<>();

                    try (GZIPInputStream gzipInputStream = new GZIPInputStream(Files.newInputStream(file.toPath()));
                         BufferedReader reader = new BufferedReader(new InputStreamReader(gzipInputStream))) {

                        String line;
                        while ((line = reader.readLine()) != null) {
                            Optional<CdnLogItem> optionalCdnLogItem = cdnLogItemParser.parse(line);
                            optionalCdnLogItem.ifPresent(cdnLogItems::add);
                        }
                    } catch (IOException e) {
                        e.printStackTrace(); // Handle the exception properly in a real application
                    }

                    resultMap.put(filePath, cdnLogItems);
                }
            }

            File[] subFolders = folder.listFiles(File::isDirectory);
            if (subFolders != null) {
                for (File subfolder : subFolders) {
                    processFolder(subfolder, resultMap);
                }
            }
        }
    }
}




